package java学习.第12章_集合框架;

import org.junit.Test;

import java.util.*;


public class C2_TreeMap {
    /**
     * TreeMap
     * 向TreeMap中添加key-value,要求key必须是由同一个类创建的对象
     * 因为要按照key进行排序:自然排序、
     */
    @Test
    public void TreeMapTest() {

        Comparator comparator = new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof User && o2 instanceof User) {
                    User u1 = (User) o1;
                    User u2 = (User) o2;
                    return Integer.compare(u1.getAge(), u2.getAge());
                } else {
                    throw new RuntimeException("类型不一样");
                }
            }
        };//定制排序
        TreeMap<User,Integer> map = new TreeMap(comparator);
        User user1 = new User("aa", 1005);
        User user2 = new User("bb", 1003);
        User user3 = new User("dd", 1008);
        User user4 = new User("dd", 1002);
        map.put(user1, 99);
        map.put(user2, 23);
        map.put(user3, 786);
        map.put(user4, 95679);


        Set entrySet = map.entrySet();
        Iterator iterator = entrySet.iterator();
        while (iterator.hasNext()) {
            Object next = iterator.next();
            Map.Entry entry = (Map.Entry) next;
            System.out.println(entry.getKey() + "----->" + entry.getValue());
        } //map最优遍历方法

        System.out.println("------------增强for-----------------------");
        for (Map.Entry entry : map.entrySet()) {
            System.out.println(entry.getKey() + "----->" + entry.getValue());

        }

    }

}
